#include  <strings.h>
#include  <stdio.h>
#include  <sys/types.h>
#include  <sys/socket.h>
#include  <sys/stat.h>
#include  <netdb.h>
#include  <unistd.h>
#include  <cstdlib>
#include  <iostream>
#include  <fcntl.h>
#include  <errno.h>

using namespace std;


/* ---------------------------------------------------------------*/
/**
 *  * 函数简介:   封装了TCP客户端连接服务器的例程
 *  *
 *  * 参数: host  主机域名或者IP
 *  * 参数: serv  主机端口号
 *  *
 *  * 返回值:     -1表示连接失败   0表示成功
 *  */
/* ---------------------------------------------------------------*/
int tcp_connect(const char *host, const char *serv)
{
    int                             sockfd, n;
    struct addrinfo hints, *res, *ressave;

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0)
        return -1;

    ressave = res;

    do {
         sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
         if (sockfd < 0)
              continue;       /* ignore this one */

         if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
              break;          /* success */

         close(sockfd);  /* ignore this one */
        } while ( (res = res->ai_next) != NULL);

    if (res == NULL)        /* errno set from final connect() */
        return -1;

    freeaddrinfo(ressave);

    return(sockfd);
}
/* end tcp_connect */

int main(int argc, char *argv[])
{
	if( argc != 2 )
	{
		cerr << "usage: scanport ip_addr" << endl;
		exit (-1);
	}

	cout << "scan begein..." << endl;

	for( int i = 1; i < 65535 ; i++ )
	{
		char port_num[10];
		sprintf(port_num,"%d",i);

		int sock = tcp_connect(argv[1],port_num);
		if( sock == -1 )
			continue;

		close(sock);
		cout << "port " << i << " is open." << endl;
	}
	
	cout << "scan done!" << endl;
}
